package com.msb.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.constant.WareConstant;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.PurchaseService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.PurchaseDoneVo;
import com.msb.mall.ware.vo.PurchaseItemDoneVo;
import com.msb.mall.ware.vo.PurchaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByStatus(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void merge(PurchaseVo purchaseVo) {
        // 采购单id
        Long purchaseId = purchaseVo.getPurchaseId();
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        // 判断采购单的状态，如果和已分配和新建状态才能合单，如果是已领取，不能合单
        if (this.getById(purchaseId).getStatus() > WareConstant.PurchaseStatusEnum.RECEIVED.getCode()) {
            return;
        }

        // 更新采购需求里面的采购单id
        List<Long> items = purchaseVo.getItems();
        final long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(e -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(e);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return purchaseDetailEntity;
        }).filter(id -> {
            PurchaseDetailEntity item = purchaseDetailService.getById(id);
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        if (list.size() > 0) {
            purchaseDetailService.updateBatchById(list);

        }
        PurchaseEntity entity = this.getById(purchaseId);
        entity.setUpdateTime(new Date());
        this.updateById(entity);
    }
    @Transactional
    @Override
    public void receive(List<Long> ids) {
        List<PurchaseEntity> list = ids.stream().map(this::getById).filter(i -> {
            if (i.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                i.setUpdateTime(new Date());
                i.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        this.updateBatchById(list);

        for (Long id : ids) {
            QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("purchase_id", id);
            List<PurchaseDetailEntity> list1 = purchaseDetailService.list(wrapper);
            List<PurchaseDetailEntity> list2 = list1.stream().map(item -> {
                item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return item;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(list2);
        }
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId(); // 采购单id
        boolean flag = true; // 默认完成采购

        for (PurchaseItemDoneVo item : purchaseDoneVo.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            // 更新采购项的状态
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 更新库存信息
                Long wareId = purchaseDetailEntity.getWareId();
                Long skuId = purchaseDetailEntity.getSkuId();
                Integer skuNum = purchaseDetailEntity.getSkuNum();
                wareSkuService.addStock(wareId, skuId, skuNum);
            }
            purchaseDetailService.updateById(purchaseDetailEntity);
        }

        // 更新采购单的状态
        PurchaseEntity entity = this.getById(id);
        entity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        entity.setUpdateTime(new Date());
        this.updateById(entity);
    }

}